<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>管理员登录</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
    <link rel="stylesheet" href="css/managerLogin.css">
</head>
<body>
<%
    // Session 检查
    HttpSession currentSession = request.getSession(false);
    String userType = (String) (currentSession != null ? currentSession.getAttribute("userType") : null);
    String adminUsername = (String) (currentSession != null ? currentSession.getAttribute("adminUsername") : null);
    
    // 如果已经是管理员登录状态，直接跳转到admin.jsp
    if (currentSession != null && "admin".equals(userType) && adminUsername != null) {
        response.sendRedirect("admin.jsp");
        return;
    }
%>

<div class="login-container">
    <div class="login-header">
        <h2><i class="fa fa-lock"></i> 管理员登录</h2>
        <p>欢迎使用管理系统</p>
    </div>

    <form id="loginForm" method="post" onsubmit="return handleFormSubmit(event)">
        <input type="hidden" name="action" value="login">
        <div class="form-group">
            <div class="input-icon">
                <i class="fa fa-user"></i>
                <input type="text" id="username" name="username" required>
                <label for="username">用户名</label>
            </div>
        </div>
        <div class="form-group">
            <div class="input-icon">
                <i class="fa fa-key"></i>
                <input type="password" id="password" name="password" required>
                <label for="password">密码</label>
            </div>
        </div>
        <div class="form-options">
            <label>
                <input type="checkbox" name="remember"> 记住我
            </label>
            <a href="#" class="forgot-password">忘记密码？</a>
        </div>
        <div id="message" class="message"></div>
        <button type="submit" class="login-button">
            <span class="button-text">登录</span>
            <i class="fa fa-arrow-right"></i>
        </button>
        <div class="register-link">
            没有账号？ <a href="managerRegister.jsp">立即注册</a>
        </div>
    </form>
</div>

<!-- 添加返回按钮 -->
<div class="back-button">
    <a href="javascript:history.back()" class="btn-back">
        <i class="fa fa-arrow-left"></i> 返回
    </a>
</div>

<style>
.btn-back {
    position: fixed;
    top: 20px;
    left: 20px;
    padding: 10px 20px;
    background-color: #f0f0f0;
    border: none;
    border-radius: 5px;
    color: #333;
    text-decoration: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 5px;
}

.btn-back:hover {
    background-color: #e0e0e0;
}
</style>

<script>
// 添加 session 检查函数
function checkAdminSession() {
    fetch('api/checkSession?type=admin')
        .then(response => response.text())
        .then(result => {
            if (result === 'admin') {
                window.location.href = 'admin.jsp';
            }
        })
        .catch(error => {
            console.error('Session check error:', error);
        });
}

// 页面加载时检查 session
document.addEventListener('DOMContentLoaded', checkAdminSession);

// 定期检查 session（每5分钟）
setInterval(checkAdminSession, 300000);

async function handleFormSubmit(event) {
    event.preventDefault();

    const formData = new URLSearchParams(new FormData(event.target));
    const submitBtn = event.target.querySelector('button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = `<i class="fa fa-spinner fa-spin"></i> 登录中...`;

    try {
        const response = await fetch('adminLoginServlet', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: formData
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const text = await response.text();
        console.log('Server response:', text);

        let data;
        try {
            data = JSON.parse(text);
        } catch (e) {
            console.error('JSON parse error:', e);
            throw new Error('Invalid JSON response');
        }

        if (data.status === 'success') {
            sessionStorage.setItem('userType', 'admin');
            window.location.href = data.redirectUrl;
        } else {
            showMessage(data.message || '登录失败', 'error');
        }
    } catch (error) {
        showMessage('网络连接错误，请稍后重试', 'error');
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = `<span class="button-text">登录</span><i class="fa fa-arrow-right"></i>`;
    }
}

function showMessage(text, type = 'error') {
    const messageEl = document.getElementById('message');
    messageEl.textContent = text;
    messageEl.className = `message ${type}`;
    messageEl.style.display = 'block';

    setTimeout(() => {
        messageEl.style.opacity = '0';
        setTimeout(() => messageEl.style.display = 'none', 500);
    }, 3000);
}
</script>
</body>
</html>